import xlwings as xw
from boot import List
import json


__all__ = ["SaveExcel"]


class SaveExcel:

    def __init__(self, file_path):
        self._file_path = file_path

    def __enter__(self):
        self._app = xw.App(visible=False, add_book=False)
        self._book = self._app.books.open("{}".format(self._file_path))
        self._sheet = self._book.sheets[0]
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()


    def save_excel(self, sale_id, cust_name, sale_datetime, sale_list: str):

        sale_number = 0  # 总件数
        total_amount = 0

        # 1.将数据写入表格中
        content: List[List[str]]= json.loads(sale_list)["content"]
        # 2.计算合计金额与总件数并设置
        for row in content:
            sale_number += int(row[1]) if row[1].replace(" ", "") != "" else 0
            total_amount += int(row[5]) if row[5].replace(" ", "") != "" else 0

        # 写入清单编号
        self._sheet.range("C2").value = sale_id
        # 写入客户姓名
        self._sheet.range("H2").value = cust_name
        # 写入发货时间
        self._sheet.range("C3").value = sale_datetime
        # 写入总件数
        self._sheet.range("H3").value = str(sale_number)
        # 写入所有数据
        self._sheet.range("B6").value = content
        # 写入总金额
        self._sheet.range("C31").value = str(total_amount)


    def close(self):
        self._book.save()
        self._book.close()
        self._app.quit()
        del self